<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>MongoDB的CURD | yili的个人小站</title><meta name="keywords" content="MongoDB"><meta name="author" content="yili"><meta name="copyright" content="yili"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="MongoDB的CURD:satellite:  本章较长，请耐心看完1.Insert Documents下面是插入单条数据，选择性的插入一个文档即可。 12345&gt; db.yili.insertOne( &amp;#123; name:&quot;sue&quot;, age:26, status:&quot;pending&quot; &amp;#125; )&amp;#123;        &quot;ac">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB的CURD">
<meta property="og:url" content="https://yili979.gitee.io/blog/2021/10/04/nosql/MongoDB%E7%9A%84CURD/index.html">
<meta property="og:site_name" content="yili的个人小站">
<meta property="og:description" content="MongoDB的CURD:satellite:  本章较长，请耐心看完1.Insert Documents下面是插入单条数据，选择性的插入一个文档即可。 12345&gt; db.yili.insertOne( &amp;#123; name:&quot;sue&quot;, age:26, status:&quot;pending&quot; &amp;#125; )&amp;#123;        &quot;ac">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://images.pexels.com/photos/844297/pexels-photo-844297.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940">
<meta property="article:published_time" content="2021-10-04T15:48:28.000Z">
<meta property="article:modified_time" content="2021-10-04T15:50:56.515Z">
<meta property="article:author" content="yili">
<meta property="article:tag" content="MongoDB">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://images.pexels.com/photos/844297/pexels-photo-844297.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"><link rel="shortcut icon" href="/blog/img/favicon.ico"><link rel="canonical" href="https://yili979.gitee.io/blog/2021/10/04/nosql/MongoDB%E7%9A%84CURD/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'MongoDB的CURD',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-10-04 23:50:56'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/blog/css/custom.css" media="defer" onload="this.media='all'"><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/10/05/BKpC6sFEo5Dl7qA.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">28</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://images.pexels.com/photos/844297/pexels-photo-844297.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=2&amp;h=650&amp;w=940')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">yili的个人小站</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">MongoDB的CURD</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-10-04T15:48:28.000Z" title="发表于 2021-10-04 23:48:28">2021-10-04</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-10-04T15:50:56.515Z" title="更新于 2021-10-04 23:50:56">2021-10-04</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/MongoDB/">MongoDB</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>13分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="MongoDB的CURD"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="MongoDB的CURD"><a href="#MongoDB的CURD" class="headerlink" title="MongoDB的CURD"></a>MongoDB的CURD</h1><h2 id="satellite-本章较长，请耐心看完"><a href="#satellite-本章较长，请耐心看完" class="headerlink" title=":satellite:  本章较长，请耐心看完"></a>:satellite:  本章较长，请耐心看完</h2><h2 id="1-Insert-Documents"><a href="#1-Insert-Documents" class="headerlink" title="1.Insert Documents"></a>1.Insert Documents</h2><p>下面是插入单条数据，选择性的插入一个文档即可。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.yili.insertOne( &#123; <span class="attr">name</span>:<span class="string">&quot;sue&quot;</span>, <span class="attr">age</span>:<span class="number">26</span>, <span class="attr">status</span>:<span class="string">&quot;pending&quot;</span> &#125; )</span><br><span class="line">&#123;</span><br><span class="line">        <span class="string">&quot;acknowledged&quot;</span> : <span class="literal">true</span>,</span><br><span class="line">        <span class="string">&quot;insertedId&quot;</span> : ObjectId(<span class="string">&quot;61134b74b4249744caec54fd&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用insertMany插入多行内容：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">db.collection.insertMany(</span><br><span class="line">   [ &lt;document 1&gt; , &lt;document 2&gt;, ... ],</span><br><span class="line">   &#123;</span><br><span class="line">      writeConcern: &lt;document&gt;,</span><br><span class="line">      ordered: &lt;boolean&gt;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>下面是插入语句，在之后的查询语句中还会用到：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.insertMany([</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;journal&quot;</span>, <span class="attr">qty</span>: <span class="number">25</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">14</span>, <span class="attr">w</span>: <span class="number">21</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;A&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;notebook&quot;</span>, <span class="attr">qty</span>: <span class="number">50</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">8.5</span>, <span class="attr">w</span>: <span class="number">11</span>, <span class="attr">uom</span>: <span class="string">&quot;in&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;A&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;paper&quot;</span>, <span class="attr">qty</span>: <span class="number">100</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">8.5</span>, <span class="attr">w</span>: <span class="number">11</span>, <span class="attr">uom</span>: <span class="string">&quot;in&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;D&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;planner&quot;</span>, <span class="attr">qty</span>: <span class="number">75</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">22.85</span>, <span class="attr">w</span>: <span class="number">30</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;D&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;postcard&quot;</span>, <span class="attr">qty</span>: <span class="number">45</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">10</span>, <span class="attr">w</span>: <span class="number">15.25</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;A&quot;</span> &#125;</span><br><span class="line">]);</span><br></pre></td></tr></table></figure>

<h2 id="2-Query-Documents"><a href="#2-Query-Documents" class="headerlink" title="2.Query Documents"></a>2.Query Documents</h2><p><strong>和sql中语句类似，mongoDB在查询数据的时候同时也会带有选择性的条件</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> inventory <span class="keyword">WHERE</span> status <span class="operator">=</span> &quot;D&quot;</span><br></pre></td></tr></table></figure>

<hr>
<p><strong>不过形式有所不同，格式如下：</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.collection.find(query, projection)</span><br></pre></td></tr></table></figure>

<h3 id="MongoDB-与-RDBMS-Where-语句比较"><a href="#MongoDB-与-RDBMS-Where-语句比较" class="headerlink" title="MongoDB 与 RDBMS Where 语句比较"></a>MongoDB 与 RDBMS Where 语句比较</h3><p>如果你熟悉常规的 SQL 数据，通过下表可以更好的理解 MongoDB 的条件语句查询：</p>
<table>
<thead>
<tr>
<th align="left">操作</th>
<th align="left">格式</th>
<th align="left">范例</th>
<th align="left">RDBMS中的类似语句</th>
</tr>
</thead>
<tbody><tr>
<td align="left">等于</td>
<td align="left"><code>&#123;&lt;key&gt;:&lt;value&gt;</code>}</td>
<td align="left"><code>db.col.find(&#123;&quot;by&quot;:&quot;菜鸟教程&quot;&#125;).pretty()</code></td>
<td align="left"><code>where by = &#39;菜鸟教程&#39;</code></td>
</tr>
<tr>
<td align="left">小于</td>
<td align="left"><code>&#123;&lt;key&gt;:&#123;$lt:&lt;value&gt;&#125;&#125;</code></td>
<td align="left"><code>db.col.find(&#123;&quot;likes&quot;:&#123;$lt:50&#125;&#125;).pretty()</code></td>
<td align="left"><code>where likes &lt; 50</code></td>
</tr>
<tr>
<td align="left">小于或等于</td>
<td align="left"><code>&#123;&lt;key&gt;:&#123;$lte:&lt;value&gt;&#125;&#125;</code></td>
<td align="left"><code>db.col.find(&#123;&quot;likes&quot;:&#123;$lte:50&#125;&#125;).pretty()</code></td>
<td align="left"><code>where likes &lt;= 50</code></td>
</tr>
<tr>
<td align="left">大于</td>
<td align="left"><code>&#123;&lt;key&gt;:&#123;$gt:&lt;value&gt;&#125;&#125;</code></td>
<td align="left"><code>db.col.find(&#123;&quot;likes&quot;:&#123;$gt:50&#125;&#125;).pretty()</code></td>
<td align="left"><code>where likes &gt; 50</code></td>
</tr>
<tr>
<td align="left">大于或等于</td>
<td align="left"><code>&#123;&lt;key&gt;:&#123;$gte:&lt;value&gt;&#125;&#125;</code></td>
<td align="left"><code>db.col.find(&#123;&quot;likes&quot;:&#123;$gte:50&#125;&#125;).pretty()</code></td>
<td align="left"><code>where likes &gt;= 50</code></td>
</tr>
<tr>
<td align="left">不等于</td>
<td align="left"><code>&#123;&lt;key&gt;:&#123;$ne:&lt;value&gt;&#125;&#125;</code></td>
<td align="left"><code>db.col.find(&#123;&quot;likes&quot;:&#123;$ne:50&#125;&#125;).pretty()</code></td>
<td align="left"><code>where likes != 50</code></td>
</tr>
</tbody></table>
<p><strong>下面是对小于符号的测试：</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.inventory.find( &#123; <span class="attr">qty</span> : &#123;<span class="attr">$lt</span>:<span class="number">40</span>&#125; &#125; ).pretty()</span><br><span class="line">&#123;</span><br><span class="line">        <span class="string">&quot;_id&quot;</span> : ObjectId(<span class="string">&quot;61134f0bb4249744caec5501&quot;</span>),</span><br><span class="line">        <span class="string">&quot;item&quot;</span> : <span class="string">&quot;journal&quot;</span>,</span><br><span class="line">        <span class="string">&quot;qty&quot;</span> : <span class="number">25</span>,</span><br><span class="line">        <span class="string">&quot;size&quot;</span> : &#123;</span><br><span class="line">                <span class="string">&quot;h&quot;</span> : <span class="number">14</span>,</span><br><span class="line">                <span class="string">&quot;w&quot;</span> : <span class="number">21</span>,</span><br><span class="line">                <span class="string">&quot;uom&quot;</span> : <span class="string">&quot;cm&quot;</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="string">&quot;status&quot;</span> : <span class="string">&quot;A&quot;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="MongoDB中使用AND操作符"><a href="#MongoDB中使用AND操作符" class="headerlink" title="MongoDB中使用AND操作符"></a>MongoDB中使用AND操作符</h3><p>在mongoDB中使用and十分简单</p>
<p>就是使用<code>,</code>来将两个表达式分割开来，即代表使用的是and操作符。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.find( &#123; <span class="attr">status</span>: <span class="string">&quot;A&quot;</span>, <span class="attr">qty</span>: &#123; <span class="attr">$lt</span>: <span class="number">30</span> &#125; &#125; )</span><br></pre></td></tr></table></figure>

<p><strong>等效于sql中的语句：</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> inventory <span class="keyword">WHERE</span> status <span class="operator">=</span> &quot;A&quot; <span class="keyword">OR</span> qty <span class="operator">&lt;</span> <span class="number">30</span></span><br></pre></td></tr></table></figure>

<h3 id="MongoDB中使用OR操作符"><a href="#MongoDB中使用OR操作符" class="headerlink" title="MongoDB中使用OR操作符"></a>MongoDB中使用OR操作符</h3><p>即在最开始的位置添加一个$or符号，然后加入一个数组的符号[]，即代表后面的逗号代表的是OR符号</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.find( &#123; <span class="attr">$or</span>: [ &#123; <span class="attr">status</span>: <span class="string">&quot;A&quot;</span> &#125;, &#123; <span class="attr">qty</span>: &#123; <span class="attr">$lt</span>: <span class="number">30</span> &#125; &#125; ] &#125; )</span><br></pre></td></tr></table></figure>

<p><strong>等效于sql中的语句：</strong></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> inventory <span class="keyword">WHERE</span> status <span class="operator">=</span> &quot;A&quot; <span class="keyword">OR</span> qty <span class="operator">&lt;</span> <span class="number">30</span></span><br></pre></td></tr></table></figure>

<p>将AND操作符和OR操作符联合进行使用：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.find( &#123;</span><br><span class="line">     <span class="attr">status</span>: <span class="string">&quot;A&quot;</span>,</span><br><span class="line">     <span class="attr">$or</span>: [ &#123; <span class="attr">qty</span>: &#123; <span class="attr">$lt</span>: <span class="number">30</span> &#125; &#125;, &#123; <span class="attr">item</span>: <span class="regexp">/^p/</span> &#125; ]</span><br><span class="line">&#125; )</span><br></pre></td></tr></table></figure>



<h3 id="对数组进行查询"><a href="#对数组进行查询" class="headerlink" title="对数组进行查询"></a>对数组进行查询</h3><p>给予一个集合中，注意到tags和dim_cm中所包含的内容为数组的形式，那么如何对数组的形式来进行查询呢？</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.insertMany([</span><br><span class="line">   &#123; item: &quot;journal&quot;, qty: 25, tags: [&quot;blank&quot;, &quot;red&quot;], dim_cm: [ 14, 21 ] &#125;,</span><br><span class="line">   &#123; item: &quot;notebook&quot;, qty: 50, tags: [&quot;red&quot;, &quot;blank&quot;], dim_cm: [ 14, 21 ] &#125;,</span><br><span class="line">   &#123; item: &quot;paper&quot;, qty: 100, tags: [&quot;red&quot;, &quot;blank&quot;, &quot;plain&quot;], dim_cm: [ 14, 21 ] &#125;,</span><br><span class="line">   &#123; item: &quot;planner&quot;, qty: 75, tags: [&quot;blank&quot;, &quot;red&quot;], dim_cm: [ 22.85, 30 ] &#125;,</span><br><span class="line">   &#123; item: &quot;postcard&quot;, qty: 45, tags: [&quot;blue&quot;], dim_cm: [ 10, 15.25 ] &#125;</span><br><span class="line">]);</span><br></pre></td></tr></table></figure>

<ul>
<li><strong>限定查询</strong></li>
</ul>
<p>如果你使用下面的方式来进行查询，得到的是固定顺序且仅包含所查询元素的方式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.find( &#123; <span class="attr">tags</span>: [<span class="string">&quot;red&quot;</span>, <span class="string">&quot;blank&quot;</span>] &#125; )</span><br><span class="line">&#123;</span><br><span class="line">        <span class="string">&quot;_id&quot;</span> : ObjectId(<span class="string">&quot;611369afb4249744caec5507&quot;</span>),</span><br><span class="line">        <span class="string">&quot;item&quot;</span> : <span class="string">&quot;notebook&quot;</span>,</span><br><span class="line">        <span class="string">&quot;qty&quot;</span> : <span class="number">50</span>,</span><br><span class="line">        <span class="string">&quot;tags&quot;</span> : [</span><br><span class="line">                <span class="string">&quot;red&quot;</span>,</span><br><span class="line">                <span class="string">&quot;blank&quot;</span></span><br><span class="line">        ],</span><br><span class="line">        <span class="string">&quot;dim_cm&quot;</span> : [</span><br><span class="line">                <span class="number">14</span>,</span><br><span class="line">                <span class="number">21</span></span><br><span class="line">        ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><strong>全查询</strong></li>
</ul>
<p>如果想要查询包含所示的元素，则需要使用<code>$all</code>操作符来进行查询：</p>
<p>查询到的结果是只包含这种的结果</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"> db.inventory.find( &#123; <span class="attr">tags</span>: &#123; <span class="attr">$all</span>: [<span class="string">&quot;red&quot;</span>, <span class="string">&quot;blank&quot;</span>] &#125; &#125;,&#123; <span class="attr">tags</span>:<span class="number">1</span> &#125; ).pretty()</span><br><span class="line">&#123;</span><br><span class="line">        <span class="string">&quot;_id&quot;</span> : ObjectId(<span class="string">&quot;611369afb4249744caec5506&quot;</span>),</span><br><span class="line">        <span class="string">&quot;tags&quot;</span> : [</span><br><span class="line">                <span class="string">&quot;blank&quot;</span>,</span><br><span class="line">                <span class="string">&quot;red&quot;</span></span><br><span class="line">        ]</span><br><span class="line">&#125;</span><br><span class="line">&#123;</span><br><span class="line">        <span class="string">&quot;_id&quot;</span> : ObjectId(<span class="string">&quot;611369afb4249744caec5507&quot;</span>),</span><br><span class="line">        <span class="string">&quot;tags&quot;</span> : [</span><br><span class="line">                <span class="string">&quot;red&quot;</span>,</span><br><span class="line">                <span class="string">&quot;blank&quot;</span></span><br><span class="line">        ]</span><br><span class="line">&#125;</span><br><span class="line">&#123;</span><br><span class="line">        <span class="string">&quot;_id&quot;</span> : ObjectId(<span class="string">&quot;611369afb4249744caec5508&quot;</span>),</span><br><span class="line">        <span class="string">&quot;tags&quot;</span> : [</span><br><span class="line">                <span class="string">&quot;red&quot;</span>,</span><br><span class="line">                <span class="string">&quot;blank&quot;</span>,</span><br><span class="line">                <span class="string">&quot;plain&quot;</span></span><br><span class="line">        ]</span><br><span class="line">&#125;</span><br><span class="line">&#123;</span><br><span class="line">        <span class="string">&quot;_id&quot;</span> : ObjectId(<span class="string">&quot;611369afb4249744caec5509&quot;</span>),</span><br><span class="line">        <span class="string">&quot;tags&quot;</span> : [</span><br><span class="line">                <span class="string">&quot;blank&quot;</span>,</span><br><span class="line">                <span class="string">&quot;red&quot;</span></span><br><span class="line">        ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><strong>单个查询</strong></li>
</ul>
<p>对在数组中的元素进行单个查询，只需要为一个数组元素进行指定一个元素即可：</p>
<p><code>tags: &quot;plain&quot;</code>:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.inventory.find( &#123; <span class="attr">tags</span>: <span class="string">&quot;plain&quot;</span>  &#125;,&#123; <span class="attr">tags</span>:<span class="number">1</span>&#125; ).pretty()</span><br><span class="line">&#123;</span><br><span class="line">        <span class="string">&quot;_id&quot;</span> : ObjectId(<span class="string">&quot;611369afb4249744caec5508&quot;</span>),</span><br><span class="line">        <span class="string">&quot;tags&quot;</span> : [</span><br><span class="line">                <span class="string">&quot;red&quot;</span>,</span><br><span class="line">                <span class="string">&quot;blank&quot;</span>,</span><br><span class="line">                <span class="string">&quot;plain&quot;</span></span><br><span class="line">        ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><strong>查询特定长度的数组</strong></li>
</ul>
<p>直接使用<code>$size</code>即可得到固定长度的数组。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.inventory.find( &#123; <span class="attr">tags</span>: &#123;<span class="attr">$size</span> : <span class="number">3</span>&#125;  &#125;,&#123; <span class="attr">tags</span>:<span class="number">1</span>&#125; ).pretty()</span><br><span class="line">&#123;</span><br><span class="line">        <span class="string">&quot;_id&quot;</span> : ObjectId(<span class="string">&quot;611369afb4249744caec5508&quot;</span>),</span><br><span class="line">        <span class="string">&quot;tags&quot;</span> : [</span><br><span class="line">                <span class="string">&quot;red&quot;</span>,</span><br><span class="line">                <span class="string">&quot;blank&quot;</span>,</span><br><span class="line">                <span class="string">&quot;plain&quot;</span></span><br><span class="line">        ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><strong>满足多个条件的数组元素的查询</strong></li>
</ul>
<p>使用这个标签来进行查询<code>$elemMatch</code>:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.inventory.find(&#123;<span class="attr">dim_cm</span>:&#123;<span class="attr">$elemMatch</span>:&#123;<span class="attr">$lt</span>:<span class="number">15</span>,<span class="attr">$gt</span>:<span class="number">11</span>&#125;&#125;&#125;,&#123;<span class="string">&quot;dim_cm&quot;</span>:<span class="number">1</span>&#125;).pretty()</span><br><span class="line">&#123; <span class="string">&quot;_id&quot;</span> : ObjectId(<span class="string">&quot;611369afb4249744caec5506&quot;</span>), <span class="string">&quot;dim_cm&quot;</span> : [ <span class="number">14</span>, <span class="number">21</span> ] &#125;</span><br><span class="line">&#123; <span class="string">&quot;_id&quot;</span> : ObjectId(<span class="string">&quot;611369afb4249744caec5507&quot;</span>), <span class="string">&quot;dim_cm&quot;</span> : [ <span class="number">14</span>, <span class="number">21</span> ] &#125;</span><br><span class="line">&#123; <span class="string">&quot;_id&quot;</span> : ObjectId(<span class="string">&quot;611369afb4249744caec5508&quot;</span>), <span class="string">&quot;dim_cm&quot;</span> : [ <span class="number">14</span>, <span class="number">21</span> ] &#125;</span><br></pre></td></tr></table></figure>

<h3 id="对文档数组进行查询"><a href="#对文档数组进行查询" class="headerlink" title="对文档数组进行查询"></a>对文档数组进行查询</h3><p><strong>给予</strong>如下的集合结构：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.insertMany( [</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;journal&quot;</span>, <span class="attr">instock</span>: [ &#123; <span class="attr">warehouse</span>: <span class="string">&quot;A&quot;</span>, <span class="attr">qty</span>: <span class="number">5</span> &#125;, &#123; <span class="attr">warehouse</span>: <span class="string">&quot;C&quot;</span>, <span class="attr">qty</span>: <span class="number">15</span> &#125; ] &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;notebook&quot;</span>, <span class="attr">instock</span>: [ &#123; <span class="attr">warehouse</span>: <span class="string">&quot;C&quot;</span>, <span class="attr">qty</span>: <span class="number">5</span> &#125; ] &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;paper&quot;</span>, <span class="attr">instock</span>: [ &#123; <span class="attr">warehouse</span>: <span class="string">&quot;A&quot;</span>, <span class="attr">qty</span>: <span class="number">60</span> &#125;, &#123; <span class="attr">warehouse</span>: <span class="string">&quot;B&quot;</span>, <span class="attr">qty</span>: <span class="number">15</span> &#125; ] &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;planner&quot;</span>, <span class="attr">instock</span>: [ &#123; <span class="attr">warehouse</span>: <span class="string">&quot;A&quot;</span>, <span class="attr">qty</span>: <span class="number">40</span> &#125;, &#123; <span class="attr">warehouse</span>: <span class="string">&quot;B&quot;</span>, <span class="attr">qty</span>: <span class="number">5</span> &#125; ] &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;postcard&quot;</span>, <span class="attr">instock</span>: [ &#123; <span class="attr">warehouse</span>: <span class="string">&quot;B&quot;</span>, <span class="attr">qty</span>: <span class="number">15</span> &#125;, &#123; <span class="attr">warehouse</span>: <span class="string">&quot;C&quot;</span>, <span class="attr">qty</span>: <span class="number">35</span> &#125; ] &#125;</span><br><span class="line">]);</span><br></pre></td></tr></table></figure>

<p>如果想要对文档数组进行查询，最基础的是写上其中的一个限定的对象，例如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.find( &#123; <span class="string">&quot;instock&quot;</span>: &#123; <span class="attr">warehouse</span>: <span class="string">&quot;A&quot;</span>, <span class="attr">qty</span>: <span class="number">5</span> &#125; &#125; )</span><br><span class="line">&gt; db.inventory.find( &#123; <span class="string">&quot;instock&quot;</span>: &#123; <span class="attr">warehouse</span>: <span class="string">&quot;A&quot;</span>, <span class="attr">qty</span>: <span class="number">5</span> &#125; &#125; ).pretty()</span><br><span class="line">&#123;</span><br><span class="line">        <span class="string">&quot;_id&quot;</span> : ObjectId(<span class="string">&quot;6113cb06b4249744caec550b&quot;</span>),</span><br><span class="line">        <span class="string">&quot;item&quot;</span> : <span class="string">&quot;journal&quot;</span>,</span><br><span class="line">        <span class="string">&quot;instock&quot;</span> : [</span><br><span class="line">                &#123;</span><br><span class="line">                        <span class="string">&quot;warehouse&quot;</span> : <span class="string">&quot;A&quot;</span>,</span><br><span class="line">                        <span class="string">&quot;qty&quot;</span> : <span class="number">5</span></span><br><span class="line">                &#125;,</span><br><span class="line">                &#123;</span><br><span class="line">                        <span class="string">&quot;warehouse&quot;</span> : <span class="string">&quot;C&quot;</span>,</span><br><span class="line">                        <span class="string">&quot;qty&quot;</span> : <span class="number">15</span></span><br><span class="line">                &#125;</span><br><span class="line">        ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>但是如果出现文档中的顺序不对时，是无法对这个结构进行查询的：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.find( &#123; <span class="string">&quot;instock&quot;</span>: &#123; <span class="attr">qty</span>: <span class="number">5</span>, <span class="attr">warehouse</span>: <span class="string">&quot;A&quot;</span> &#125; &#125; )</span><br></pre></td></tr></table></figure>

<ul>
<li><strong>限定符来进行查询</strong></li>
</ul>
<p>下面的示例查询 instock 数组中至少有一个嵌入文档包含大于10且小于或等于20的字段 qty 的文档:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.find( &#123; <span class="string">&quot;instock&quot;</span>: &#123; <span class="attr">$elemMatch</span>: &#123; <span class="attr">qty</span>: &#123; <span class="attr">$gt</span>: <span class="number">10</span>, <span class="attr">$lte</span>: <span class="number">20</span> &#125; &#125; &#125; &#125; )</span><br></pre></td></tr></table></figure>

<p>如果不添加elemMatch，则表示这个数组中至少有文档满足其中的一个条件（不太常用）。</p>
<h3 id="对空值null进行查询"><a href="#对空值null进行查询" class="headerlink" title="对空值null进行查询"></a>对空值null进行查询</h3><p>首先添加带有null的文档结构：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.insertMany([</span><br><span class="line">   &#123; <span class="attr">_id</span>: <span class="number">1</span>, <span class="attr">item</span>: <span class="literal">null</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">_id</span>: <span class="number">2</span> &#125;</span><br><span class="line">])</span><br></pre></td></tr></table></figure>

<p>但是如果直接对null值进行查询，则会直接出现问题，比如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.inventory.find()</span><br><span class="line">&#123; <span class="string">&quot;_id&quot;</span> : <span class="number">1</span>, <span class="string">&quot;item&quot;</span> : <span class="literal">null</span> &#125;</span><br><span class="line">&#123; <span class="string">&quot;_id&quot;</span> : <span class="number">2</span> &#125;</span><br></pre></td></tr></table></figure>

<p>使用<code>$type:10</code>就是直接对类型进行判断，可以查看是否满足null。</p>
<p>同时也可以使用<code>$exists:false</code>来判断这个元素是否存在某个固定的值。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.inventory.find(&#123;<span class="attr">item</span>:&#123;<span class="attr">$type</span>:<span class="number">10</span>&#125;&#125;)</span><br><span class="line">&#123; <span class="string">&quot;_id&quot;</span> : <span class="number">1</span>, <span class="string">&quot;item&quot;</span> : <span class="literal">null</span> &#125;</span><br><span class="line">&gt; db.inventory.find(&#123;<span class="attr">item</span>:&#123;<span class="attr">$exists</span>:<span class="literal">false</span>&#125;&#125;)</span><br><span class="line">&#123; <span class="string">&quot;_id&quot;</span> : <span class="number">2</span> &#125;</span><br></pre></td></tr></table></figure>

<h3 id="projection-参数的使用方法"><a href="#projection-参数的使用方法" class="headerlink" title="projection 参数的使用方法"></a>projection 参数的使用方法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.collection.find(query, projection)</span><br></pre></td></tr></table></figure>

<p>若不指定 projection，则默认返回所有键，指定 projection 格式如下，有两种模式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.collection.find(query, &#123;<span class="attr">title</span>: <span class="number">1</span>, <span class="attr">by</span>: <span class="number">1</span>&#125;) <span class="comment">// inclusion模式 指定返回的键，不返回其他键</span></span><br><span class="line">db.collection.find(query, &#123;<span class="attr">title</span>: <span class="number">0</span>, <span class="attr">by</span>: <span class="number">0</span>&#125;) <span class="comment">// exclusion模式 指定不返回的键,返回其他键</span></span><br></pre></td></tr></table></figure>

<p>_id 键默认返回，需要主动指定 _id:0 才会隐藏</p>
<p><strong>两种模式不可混用</strong>（因为这样的话无法推断其他键是否应返回）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.collection.find(query, &#123;<span class="attr">title</span>: <span class="number">1</span>, <span class="attr">by</span>: <span class="number">0</span>&#125;) <span class="comment">// 错误</span></span><br></pre></td></tr></table></figure>

<p><strong>只能全1或全0</strong>，<strong>除了在inclusion模式时可以指定_id为0</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.collection.find(query, &#123;<span class="attr">_id</span>:<span class="number">0</span>, <span class="attr">title</span>: <span class="number">1</span>, <span class="attr">by</span>: <span class="number">1</span>&#125;) <span class="comment">// 正确</span></span><br></pre></td></tr></table></figure>

<h2 id="3-Update-Documents"><a href="#3-Update-Documents" class="headerlink" title="3.Update Documents"></a>3.Update Documents</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.insertMany( [</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;canvas&quot;</span>, <span class="attr">qty</span>: <span class="number">100</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">28</span>, <span class="attr">w</span>: <span class="number">35.5</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;A&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;journal&quot;</span>, <span class="attr">qty</span>: <span class="number">25</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">14</span>, <span class="attr">w</span>: <span class="number">21</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;A&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;mat&quot;</span>, <span class="attr">qty</span>: <span class="number">85</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">27.9</span>, <span class="attr">w</span>: <span class="number">35.5</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;A&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;mousepad&quot;</span>, <span class="attr">qty</span>: <span class="number">25</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">19</span>, <span class="attr">w</span>: <span class="number">22.85</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;P&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;notebook&quot;</span>, <span class="attr">qty</span>: <span class="number">50</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">8.5</span>, <span class="attr">w</span>: <span class="number">11</span>, <span class="attr">uom</span>: <span class="string">&quot;in&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;P&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;paper&quot;</span>, <span class="attr">qty</span>: <span class="number">100</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">8.5</span>, <span class="attr">w</span>: <span class="number">11</span>, <span class="attr">uom</span>: <span class="string">&quot;in&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;D&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;planner&quot;</span>, <span class="attr">qty</span>: <span class="number">75</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">22.85</span>, <span class="attr">w</span>: <span class="number">30</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;D&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;postcard&quot;</span>, <span class="attr">qty</span>: <span class="number">45</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">10</span>, <span class="attr">w</span>: <span class="number">15.25</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;A&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;sketchbook&quot;</span>, <span class="attr">qty</span>: <span class="number">80</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">14</span>, <span class="attr">w</span>: <span class="number">21</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;A&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;sketch pad&quot;</span>, <span class="attr">qty</span>: <span class="number">95</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">22.85</span>, <span class="attr">w</span>: <span class="number">30.5</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;A&quot;</span> &#125;</span><br><span class="line">] );</span><br></pre></td></tr></table></figure>

<p><strong>对一个文档进行更新：</strong></p>
<p>使用updateOne() 方法来进行操作：</p>
<p>格式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">db.collection.updateOne(</span><br><span class="line">   &lt;filter&gt;,</span><br><span class="line">   &lt;update&gt;,</span><br><span class="line">   &#123;</span><br><span class="line">     <span class="attr">upsert</span>: &lt;boolean&gt;,</span><br><span class="line">     writeConcern: &lt;<span class="built_in">document</span>&gt;,</span><br><span class="line">     collation: &lt;<span class="built_in">document</span>&gt;,</span><br><span class="line">     arrayFilters: [ &lt;filterdocument1&gt;, ... ]</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>最重要的是<code>filter&gt;</code>和<code>update</code>，第一个是对所有数据进行筛选，第二个是将对应的数据进行修改。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.updateOne(</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;mat&quot;</span> &#125;,</span><br><span class="line">   &#123;</span><br><span class="line">     <span class="attr">$set</span>: &#123; <span class="string">&quot;size.uom&quot;</span>: <span class="string">&quot;cm&quot;</span>, <span class="attr">status</span>: <span class="string">&quot;P&quot;</span> &#125;,</span><br><span class="line">     <span class="attr">$currentDate</span>: &#123; <span class="attr">lastModified</span>: <span class="literal">true</span> &#125;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>**$currentDate: { lastModified: true }**，就是将文档中名为的元素<code>lastModified</code>修改为当前的时间。</p>
<p>更多的操作符可以参考 <a href="CURD%E7%9A%84%E5%85%B7%E4%BD%93%E6%93%8D%E4%BD%9C%E7%AC%A6.md">CURD的具体操作符</a> ，不做过多的展示了。</p>
<h2 id="4-Delete-Documents"><a href="#4-Delete-Documents" class="headerlink" title="4.Delete Documents"></a>4.Delete Documents</h2><p>对以下的数据进行操作：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.insertMany( [</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;journal&quot;</span>, <span class="attr">qty</span>: <span class="number">25</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">14</span>, <span class="attr">w</span>: <span class="number">21</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;A&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;notebook&quot;</span>, <span class="attr">qty</span>: <span class="number">50</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">8.5</span>, <span class="attr">w</span>: <span class="number">11</span>, <span class="attr">uom</span>: <span class="string">&quot;in&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;P&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;paper&quot;</span>, <span class="attr">qty</span>: <span class="number">100</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">8.5</span>, <span class="attr">w</span>: <span class="number">11</span>, <span class="attr">uom</span>: <span class="string">&quot;in&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;D&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;planner&quot;</span>, <span class="attr">qty</span>: <span class="number">75</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">22.85</span>, <span class="attr">w</span>: <span class="number">30</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;D&quot;</span> &#125;,</span><br><span class="line">   &#123; <span class="attr">item</span>: <span class="string">&quot;postcard&quot;</span>, <span class="attr">qty</span>: <span class="number">45</span>, <span class="attr">size</span>: &#123; <span class="attr">h</span>: <span class="number">10</span>, <span class="attr">w</span>: <span class="number">15.25</span>, <span class="attr">uom</span>: <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status</span>: <span class="string">&quot;A&quot;</span> &#125;,</span><br><span class="line">] );</span><br></pre></td></tr></table></figure>

<p><strong>删除所有在集合中的文档</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.deleteMany(&#123;&#125;)</span><br></pre></td></tr></table></figure>

<p><strong>删除所有条件匹配的文档</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.deleteMany(&#123; <span class="attr">status</span> : <span class="string">&quot;A&quot;</span> &#125;)</span><br></pre></td></tr></table></figure>

<p><strong>删除一个条件匹配的文档</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.inventory.deleteOne(&#123; <span class="attr">status</span> : <span class="string">&quot;A&quot;</span> &#125;)</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">yili</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://yili979.gitee.io/blog/2021/10/04/nosql/MongoDB%E7%9A%84CURD/">https://yili979.gitee.io/blog/2021/10/04/nosql/MongoDB%E7%9A%84CURD/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://yili979.gitee.io/blog" target="_blank">yili的个人小站</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/MongoDB/">MongoDB</a></div><div class="post_share"><div class="social-share" data-image="https://images.pexels.com/photos/844297/pexels-photo-844297.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=2&amp;h=650&amp;w=940" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2021/10/05/java/Java8%E6%B5%81%E5%A4%84%E7%90%86/"><img class="prev-cover" src="https://i.loli.net/2021/10/04/7PWqmtGLMs3hign.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Java8流处理</div></div></a></div><div class="next-post pull-right"><a href="/blog/2021/10/04/mysql/InnoDB%E4%BA%8B%E5%8A%A1/"><img class="next-cover" src="https://i.loli.net/2021/10/04/7PWqmtGLMs3hign.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">InnoDB事务</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/10/05/BKpC6sFEo5Dl7qA.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">yili</div><div class="author-info__description">身骑白马</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">28</div></a></div><div class="card-info-data-item is-center"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a></div><div class="card-info-data-item is-center"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/qiuyuyin"><i class="fab fa-github"></i><span>github🍟</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">啦啦啦，写的不好还请见谅😉<div class="twopeople"><div class="twopeople"><div class="container"style="height:200px;"><canvas class="illo"width="800"height="800"style="max-width: 200px; max-height: 200px; touch-action: none; width: 640px; height: 640px;"></canvas></div><script src="js/twopeople1.js"></script><script src="js/zdog.dist.js"></script><script id="rendered-js"src="js/twopeople.js"></script><style>.twopeople{margin:0;align-items:center;justify-content:center;text-align:center}canvas{display:block;margin:0 auto;cursor:move}</style></div></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#MongoDB%E7%9A%84CURD"><span class="toc-text">MongoDB的CURD</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#satellite-%E6%9C%AC%E7%AB%A0%E8%BE%83%E9%95%BF%EF%BC%8C%E8%AF%B7%E8%80%90%E5%BF%83%E7%9C%8B%E5%AE%8C"><span class="toc-text">:satellite:  本章较长，请耐心看完</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-Insert-Documents"><span class="toc-text">1.Insert Documents</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-Query-Documents"><span class="toc-text">2.Query Documents</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#MongoDB-%E4%B8%8E-RDBMS-Where-%E8%AF%AD%E5%8F%A5%E6%AF%94%E8%BE%83"><span class="toc-text">MongoDB 与 RDBMS Where 语句比较</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MongoDB%E4%B8%AD%E4%BD%BF%E7%94%A8AND%E6%93%8D%E4%BD%9C%E7%AC%A6"><span class="toc-text">MongoDB中使用AND操作符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#MongoDB%E4%B8%AD%E4%BD%BF%E7%94%A8OR%E6%93%8D%E4%BD%9C%E7%AC%A6"><span class="toc-text">MongoDB中使用OR操作符</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E6%95%B0%E7%BB%84%E8%BF%9B%E8%A1%8C%E6%9F%A5%E8%AF%A2"><span class="toc-text">对数组进行查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E6%96%87%E6%A1%A3%E6%95%B0%E7%BB%84%E8%BF%9B%E8%A1%8C%E6%9F%A5%E8%AF%A2"><span class="toc-text">对文档数组进行查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E7%A9%BA%E5%80%BCnull%E8%BF%9B%E8%A1%8C%E6%9F%A5%E8%AF%A2"><span class="toc-text">对空值null进行查询</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#projection-%E5%8F%82%E6%95%B0%E7%9A%84%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95"><span class="toc-text">projection 参数的使用方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-Update-Documents"><span class="toc-text">3.Update Documents</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-Delete-Documents"><span class="toc-text">4.Delete Documents</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/03/08/something-about-crypto/" title="something about crypto"><img src="https://yili979.oss-cn-beijing.aliyuncs.com/img/image-20220124000713258.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="something about crypto"/></a><div class="content"><a class="title" href="/blog/2022/03/08/something-about-crypto/" title="something about crypto">something about crypto</a><time datetime="2022-03-08T12:01:13.000Z" title="发表于 2022-03-08 20:01:13">2022-03-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/03/08/golang%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="golang内存管理"><img src="https://yili979.oss-cn-beijing.aliyuncs.com/img/202203081958270.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="golang内存管理"/></a><div class="content"><a class="title" href="/blog/2022/03/08/golang%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="golang内存管理">golang内存管理</a><time datetime="2022-03-08T11:55:30.000Z" title="发表于 2022-03-08 19:55:30">2022-03-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/03/08/%E9%89%B4%E6%9D%83%E7%B3%BB%E7%BB%9F/" title="鉴权系统"><img src="https://yili979.oss-cn-beijing.aliyuncs.com/img/202203081950401.jpeg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="鉴权系统"/></a><div class="content"><a class="title" href="/blog/2022/03/08/%E9%89%B4%E6%9D%83%E7%B3%BB%E7%BB%9F/" title="鉴权系统">鉴权系统</a><time datetime="2022-03-08T11:49:53.000Z" title="发表于 2022-03-08 19:49:53">2022-03-08</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By yili</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>